
$(window).load(function(){
	$.getJSON("/resources/template", function(data){
		window.loadingpane = $("#loadingpane");
		var ref = getref();
		
		var bar = new ContainerGroup("op-menu-bar");
		var barhelper = new ContainerGroup("op-menupage");
		var content = createContent(data, bar);
		buildMenuBar(bar, content, barhelper);
		var header = createHeader(content, bar, barhelper);
		var footer = createFooter(data);
		var all = new Container("op-main");
		
		all.add(header);
		all.add(content);
		all.add(footer);
		
		all.buildOn($("#body"));
		addGoogleAnalytics();
		addWindowEvents(bar, content);
		//only if the page has a reference
		gotopage(ref, bar, content);
		
	});
});

function addWindowEvents(bar, content){
	window.onpopstate = function(event) {
	    if (event.state != null) {
	    	gotopage(event.state, bar, content);
	    }
	};
}

function getref(){
	var ref = location.href;
	var i = ref.indexOf("#");
	if(i == -1) return null;
	return ref.substring(i+1);
}

function gotopage(ref, bar, content){
	if(ref == null || ref.length == 0) return;
	if(content.pages[ref] != null) {
		content.setContent({target:bar.menu(ref)});
	}
	var txt = '/pages/company/';
	if(ref.startsWith(txt)){
		content.setContent({target:bar.menu('Company')});
		setTimeout(function(){window.companypanel.menu(ref).click()},500);
		return;
	}
	txt = '/pages/products/';
	if(ref.startsWith(txt)){
		ref = ref.substring(txt.length);
		var i = ref.indexOf('/');
		if(i == -1) return;
		ref = ref.substring(0, i);
		ref = ref.charAt(0).toUpperCase() + ref.slice(1);
		content.setContent({target:{text:ref}});
	}
}

function buildMenuBar(bar, content, barhelper){
	var set = content.setContent,
		menu1 = new Menu("Home", set, barhelper),
		menu2 = new Menu("Products", set, barhelper),
		menu3 = new Menu("Company", set, barhelper),
		menu4 = new Menu("Users", set, barhelper),
		menu5 = new Menu("Contact", set, barhelper),
		link = new Anchor(new Img("/img/facebook.png").target, "http://www.facebook.com/ObjectProfile"),
		temp = new ContainerGroup("op-menurighticon");
	temp.add(link);
	link.tar("_blank").title("Facebook Page");
	bar.add(menu1).add(menu2).add(menu3).add(menu4).add(menu5).add(temp);
	bar.menu = function(ref){
		return this.elements.find(function (e){
			return ref == e.text;})
	}
	content.setContent({target:menu1});
}

function createHeader(content, bar, barhelper){
	var header = new Container("op-header");
	header.add(bar);
	header.add(barhelper);
	return header;
}

function createContent(data, bar){
	var content = new Container("op-content");
	var pages = {
			 Home:createHome,
		     Products: createProducts,
		     Company: createCompany,
		     Users: createUsers,
		     Contact: createContact,
		     Hapao: findProduct,
		     Kai: findProduct,
		     Roassal: findProduct,
		     Loom: findProduct,
		     Sunburst: findProduct,
		     "Memory Profiler": findProduct,
		     Roassal3d: findProduct,
		     GraphET: findProduct
		        };
	
	content.pages = pages;
	content.setContent = function (e){
		var direction = e.target.text;
		var block = pages[direction];
		
		pushHistory(direction);
		content.clear();
		content.target.empty();
		if(e.target && e.target.active) e.target.active();
		
		if(!block) block = nopage;
		var html = new HTML(block(data, content, bar, direction));
		html.buildOn(content.target);
	}
	
	content.canAjax = true;

	content.loadAjax = function (e){
		if(!content.canAjax) return;
		content.canAjax = false;
		var target = e.target;
		var pane = target.pane;
		$.ajax({
            url : target.pageurl,
            dataType: "text",
            success : function (text) {
            	pushHistory(target.pageurl);
                pane.html(text);
                content.canAjax = true;
                if(target.callback) target.callback(data, content, bar);
                if(target.active) target.active();
            },
            error: function(){
            	pane.html(nopage(data, content, bar));
            	content.canAjax = true;
            }
        });
	};
	return content;
}

function pushHistory(loc){
	try{
		history.pushState(loc, '',location.search +"#"+ loc);
	}catch(e){alert(e);}
}

function findProduct(data, content, bar, ref) {
	var res = createProducts(data, content, bar);
	bar.elements[1].active();
	var productMap = {};
	var k = 0;
	data.company.products.each(function (prod){
		productMap[prod.name] = k; 
		k++;
	});
	//var pindex = {'Hapao': 0, 'Kai': 1, 'Roassal':2, 'Loom':3};
	
	var i = productMap[ref];
	var reference = window.productspanel.menu.ref;
	var menu = reference.elements[i*2];
	var items = reference.elements[i*2+1];
	
	items.elements[0].target.click();
	menu.target.click();
	
	return res;
}

function nopage(data, content, bar){
	return "Page not found";
}

function createHome(data, content, bar){
	
	if(!window.homepanel){
		window.homepanel = $("#home").show();
		window.homepanel.imgs = $("#homeimgs");
		window.homepanel.twitter = $("#op-twitter");
	}
	buildHomeInfo(data, content);
	addFacebook();
	addTwitter(window.homepanel.twitter);
	return window.homepanel;
}

function buildHomeInfo(data, content){
	var products = data.company.products;
	var plataforms = data.company.plataforms;
	window.homepanel.imgs.html('');
	
	products.each(function (prod){
		var img = new Img(prod.img);
		img.target.attr("title", prod.name).click(function(e){
			e.target.text = e.target.title;
			content.setContent(e);
		});
		img.buildOn(window.homepanel.imgs);
	});
	
	$("#productsInfo").html('Our currently available products are '
		+namesAnd({arr: products, 
				   block: function(e){
					   return e.name;
				   }}));
	buildPlataformsInfo(data);
	
	var q = new Container("op-plataformsinfo");
	plataforms.each(function(e){
		var a = new Anchor("<img src='"+e.img+"'/>", e.link);
		a.tar("_blank").title(e.name);
		q.add(a);
	});
	q.buildOn($("#plataformsInfo"));
}

function buildPlataformsInfo(data, content, bar){
	var plataforms = data.company.plataforms;
	
	$(".plataformsInfo").each(function (){
		$(this).html(plataformInfo(plataforms));
	});
}

function plataformInfo(plataforms){
	return namesAnd({arr: plataforms,
			   last: " ",
			   block: function(e){
				   return "<a class='op-a' target='_blank' href='"
				   +e.link+"' title='"+e.name+"'>"+ e.name+"</a>";
			   }})
}

function namesAnd(obj){
	var txt = "", len = obj.arr.length;
	if(!obj.last) obj.last = ":";
	if(!obj.sep) obj.sep = ", ";
	if(!obj.and) obj.and = " and ";
	if(!obj.block) obj.block = function(e){return e;}
	for(var i = 0; i< len; i++){
		txt += obj.block(obj.arr[i]) +
		((i == len-1)?obj.last:
		(i == len-2)?obj.and:obj.sep);
	}
	return txt;
}

function addFacebook(){
	$("#op-facebook").html("<br><iframe src=\"http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2FObjectProfile&amp;send=false&amp;layout=standard&amp;width=300&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=80\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:300px; height:80px;\" allowTransparency=\"true\"></iframe> </br>");
}

function addTwitter(aside){
	
	aside.html('');
	
	var tw_div = $("<div></div>")
	tw_div.append( '<a class="twitter-timeline"'+
						  'height="300px" '+
						  'href="https://twitter.com/ObjectProfile" '+
						  'data-widget-id="355772677165826048">'+
						'Tweets by @ObjectProfile</a>'+
						'<script>'+
						'!function(d,s,id){\n'+
							'var js,fjs=d.getElementsByTagName(s)[0],\n'+
							   'p=/^http:/.test(d.location)?"http":"https";\n'+
							'//if(!d.getElementById(id)){\n'+
							   'js=d.createElement(s);\n'+
							   'js.id=id;js.src=p+"://platform.twitter.com/widgets.js";\n'+
							   'fjs.parentNode.insertBefore(js,fjs);}(document,"script","twitter-wjs");</script>');
	aside.append(tw_div);
}

function createProducts(data, content, bar){
	if(!window.productspanel){
		window.productspanel = $("#products").show();
		window.productspanel.desc = $("#productsdesc");
		window.productspanel.content = $("#productsContent");
		window.productspanel.menu = $("#productsmenu");
		window.productspanel.detail = $("#productsdetail");
	}
	var pane = window.productspanel;
	pane.content.html('').append(pane.detail);
	buildProductsDescription(pane, data, content);
	buildProductsMenu(pane, data, content);
	return pane;
}

function buildProductsMenu(pane, data, content){
	var container = new ContainerGroup("op-sidemenu");
	var action = function(e){
		var items = e.target.items;
		container.elements.each(function(e){
			if(e instanceof ContainerGroup)
				e.target.hide(500);
		});
		e.target.active();
		items.show(500);
		if(e.target.pageurl){
			content.loadAjax(e);
		}
	}
	function pbutton(text, obj){
		var menu = new Menu(text, action);
		var base = "/pages/products/";
		var items = new ContainerGroup("");
		var a = menu.a();
		a.items=items.target;
		items.target.hide();
		container.add(menu).add(items);
		if(obj instanceof Array){
			obj.each(function(e){
				var link =new Anchor('► '+e.n);
				var a2 = link.a();
				a2.pageurl = base+e.l;
				a2.eparent = link;
				a2.pane = pane.content;
				a2.callback = function(){
					this.eparent.parent.elements.each(function(e){
						e.removeClass("op-a-selected");
					});
					this.eparent.addClass('op-a-selected');
				};
				link.target.click(content.loadAjax);
				items.add(link);
			});
		}else{
			a.pageurl = base+obj;
			a.pane = pane.content;
		}
		
		return menu;
	}
	pbutton("Hapa'o -  Test Coverage Tool",
			[{n:"Overview", l:"hapao/overview.html"}
			,{n:"Download", l:"hapao/download.html"}
			,{n:"How To Use", l:"hapao/howtouse.html"}
			,{n:"Test Blueprint", l:"hapao/blueprint.html"}
			,{n:"Screenshots", l:"hapao/screenshots.html"}
			,{n:"Screencasts", l:"hapao/screencast.html"}]);
	pbutton("Kai - Code Execution Profiler",
			[{n:"Overview", l:"kai/overview.html"}
			,{n:"Download", l:"kai/download.html"}
			,{n:"How To Use", l:"kai/howtouse.html"}
			,{n:"Test Blueprint", l:"kai/blueprint.html"}
			,{n:"Screenshots", l:"kai/screenshots.html"}
			,{n:"Screencasts", l:"kai/screencast.html"}]);
	pbutton("Roassal",
			[{n:"Overview", l:"roassal/overview.html"}
			,{n:"Download", l:"roassal/download.html"}
			,{n:"Roassal Easel", l:"roassal/easel.html"}
			,{n:"Screenshots", l:"roassal/screenshots.html"}
			,{n:"Screencasts", l:"roassal/screencast.html"}]);
	pbutton("Loom - Thread Profiler",
			[{n:"Overview", l:"loom/overview.html"}
			,{n:"Download", l:"loom/download.html"}
			,{n:"Screenshots", l:"loom/screenshots.html"}]);
	pbutton("Sunburst",
			[{n:"Overview", l:"sunburst/overview.html"}
			,{n:"Download", l:"sunburst/download.html"}
			,{n:"Screenshots", l:"sunburst/screenshots.html"}]);
	pbutton("Memory Profiler",
			[{n:"Overview", l:"memoryprofiler/overview.html"}
			,{n:"Download", l:"memoryprofiler/download.html"}
			,{n:"Screenshots", l:"memoryprofiler/screenshots.html"}]);
	pbutton("Graph ET",
			[{n:"Overview", l:"graphet/overview.html"}
			,{n:"Download", l:"graphet/download.html"}
			,{n:"Screenshots", l:"graphet/screenshots.html"}]);
	pbutton("Roassal3D",
			[{n:"Overview", l:"roassal3d/overview.html"}
			,{n:"Download", l:"roassal3d/download.html"}
			,{n:"Screenshots", l:"roassal3d/screenshots.html"}]);
	pbutton("Licence", 'licence.html');
	pane.menu.ref = container;
	container.buildOn(pane.menu.html(''));
}


function buildProductsDescription(pane, data, content){
	var descrip = pane.desc;
	descrip.html('');
	data.company.products.each(function (e){
		if(e.available != "true") return;
		var cell = $("<div></div>"),
			img = new Img(e.img),
			a = $("<span></span>"),
			desc = $("<span></span>");
		img.target.attr('title',e.fullname).click(content.setContent);
		img.target[0].text = a[0].text = e.name;
		a.append(e.fullname).addClass("op-a")
		.attr('title', e.fullname).click(content.setContent);
		desc.append(e.detail);
		cell.append(img.target).append(a).append(desc);
		descrip.append(cell);
	});
}

function createCompany(data, content, bar){
	if(!window.companypanel){
		window.companypanel = $("#company").show();
		window.companymenu = $("#companymenu");
		window.companycontent = $("#companyContent");
	}
	var menu = window.companymenu.html('');
	var pane = window.companycontent;
	
	var container = new ContainerGroup("op-sidemenu");
	var action = content.loadAjax;
	function companyButton(text, link){
		var menu = new Menu(text, action);
		var a = menu.a();
		a.pageurl = "/pages/company/"+link;
		a.pane=pane;
		container.add(menu);
		return menu;
	};
	var menu1 = companyButton("The Company", "company.html");
	menu1.a().callback = buildPlataformsInfo;
	var menu2 = companyButton("The Team", "team.html");
	menu2.a().callback=createTeam;
	companyButton("Publications", "publications.html");
	menu1.target.click();
	container.buildOn(menu);
	
	window.companypanel.menu=function(str){
		var res = container.elements.find(function(e){
			return e.a().pageurl == str;
		})
		if(res) return res.target;
		return menu1.target;
	};
	
	return window.companypanel;
}

function createTeam(data, content, bar){
	
	var pane = $("#teamdetail");
	pane.html('');
	data.team.each(function(user){
		var cell = new Container("op-teaminfo"), 
			img = new Img(user.img),
			detail = new HTML(user.detail);
		
		img.target.attr('title', user.name);
		cell.add(img).add(detail);
		pane.append($("<h1></h1>").append(user.name));
		cell.buildOn(pane);
	});
}

function createUsers(data, content, bar){
	if(!window.userspanel){
		window.userspanel = $("#users").show();
		window.userspanel.detail = $("#usersDetail");
	}
	var pane = window.userspanel.detail;
	pane.html('');
	var users = data.company.users;
	users.each(function(user){
		var cell = new Container("userdetail");
		var imgs = new Container("userimgs");
		cell.add(imgs);
		function addimg(i, link){
			var img = new Anchor(new Img("/img/users/"+i).target, link);
			img.tar("_blank");
			imgs.add(img);
		}
		if(user.img instanceof Array){
			for(var k = 0; k<user.img.length; k++){
				addimg(user.img[k], user.link[k]);
			}
		}else addimg(user.img, user.link);
		var desc = new HTML(user.detail, "<span></span>");
		desc.addClass('op-info');
		cell.add(desc);
		if(user != users[users.length-1]) cell.add(new HTML("","<hr></hr>"));
		cell.buildOn(pane);
	});
	return window.userspanel;
}

function createContact(data, content, bar){
	if(!window.contactpanel){
		window.contactpanel = $("#contact").show();
		window.contactpanel.map = document.getElementById("map_canvas");
		var mapOptions = {
		          center: new google.maps.LatLng(-33.4573, -70.6645),
		          zoom: 3,
		          mapTypeId: google.maps.MapTypeId.ROADMAP
		        };
		var map = new google.maps.Map(window.contactpanel.map, mapOptions);
		var marker = new google.maps.Marker({
            position: new google.maps.LatLng(-33.4573, -70.6645),
            map: map
        });
	}

	return window.contactpanel;
}

function createFooter(data){
	var footer = new Container("op-footer");
	var office = new HTML("Office:");
	var phone = new HTML("Telephone:");
	var email = new HTML("E-mail:");
	[office, phone, email].each(
			function(e){ e.addClass("op-footer-title")});
	footer.add(office);
	footer.add(new HTML(data.company.office));
	footer.add(phone);
	footer.add(new HTML(data.company.telephone));
	footer.add(email);
	footer.add(new Anchor(data.company.email, 
			"mailto:"+data.company.email));
	return footer;
}

function addGoogleAnalytics(){

	var analytics = document.getElementById("analytics");
	var script = document.createElement('script');
	script.setAttribute('type', 'text/javascript');
 	script.text = "var _gaq = _gaq || []; _gaq.push(['_setAccount','UA-30414111-1']);_gaq.push(['_trackPageview']); (function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src=('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(ga,s)})()";

	analytics.appendChild(script);
};

